package com.util;

import com.jfinal.kit.LogKit;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpUtil {

    //GET
    public static final String GET = "GET";
    //POST
    public static final String POST = "POST";
    //PUT
    public static final String PUT = "PUT";
    //DELETE
    public static final String DELETE = "DELETE";

    public static HttpResponse httpGet(String url, Map<String, String> headers, int timeout, String content)
        throws Exception{

        headers = initialBasicHeader(headers, HttpUtil.GET, url);
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout));

        HttpGet get = new HttpGet(encodeUrl(url));

        for (Map.Entry<String, String> e : headers.entrySet()) {
            get.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
        }

        return httpClient.execute(get);
    }

    private static Map<String, String> initialBasicHeader(Map<String, String> headers, String method, String requestAddress)
            throws MalformedURLException {
        if (headers == null) {
            headers = new HashMap<String, String>();
        }

        URL url = new URL(requestAddress);
        StringBuilder stringBuilder = new StringBuilder();
        if (StringUtils.isNotBlank(url.getPath())) {
            stringBuilder.append(url.getPath());
        }
        if (StringUtils.isNotBlank(url.getQuery())) {
            stringBuilder.append("?");
            stringBuilder.append(url.getQuery());
        }

        return headers;
    }

    private static int getTimeout(int timeOut){
        if(0 == timeOut){
            return Constants.DEFAULT_TIMEOUT;
        }
        return timeOut;
    }

    private static String encodeUrl(String url) {
        if (StringUtils.isBlank(url)) {
            return url;
        }

        try {
            URL tmpUrl = new URL(url);
            StringBuilder sb = new StringBuilder();
            sb.append(tmpUrl.getProtocol());
            if (StringUtils.isNotBlank(tmpUrl.getProtocol())) {
                sb.append("://");
            }
            sb.append(tmpUrl.getHost());
            if (StringUtils.isNotBlank(tmpUrl.getPath())) {
                sb.append(tmpUrl.getPath());
            }
            if (StringUtils.isNotBlank(tmpUrl.getQuery())) {
                sb.append("?");

                boolean flag = false;
                for (String s : tmpUrl.getQuery().split("\\&")) {
                    if (flag) {
                        sb.append("&");
                    }

                    flag = true;
                    String key = s.split("\\=")[0];
                    String value = s.split("\\=")[1];
                    sb.append(key);
                    sb.append("=");
                    sb.append(URLEncoder.encode(value, Constants.ENCODING));
                }
            }

            return sb.toString();
        } catch (MalformedURLException e) {
            return url;
        } catch (UnsupportedEncodingException e) {
            return url;
        }
    }

    public static void main(String[] args) throws Exception {

        String url = "http://api.map.baidu.com/geocoder/v2/?address=上海闵行区龙柏二村82号"
                + "&output=json&ak=m07L7mGBXlGCG3NVxlOYKCdsxl7o3swL";
        HttpResponse response = HttpUtil.httpGet(url, null, 0, null);

        String  ret = EntityUtils.toString(response.getEntity(), "UTF-8");

        LogKit.info(ret);

        Map retMap = JsonUtil.getMap4Json(ret);
        String result = retMap.get("result")+"";
        LogKit.info(result);
        Map resultMap = JsonUtil.getMap4Json(result);
        String location = resultMap.get("location")+"";
        Map locaTionMap = JsonUtil.getMap4Json(location);
        String lng = locaTionMap.get("lng")+"";
        String lat = locaTionMap.get("lat")+"";

        LogKit.info("lng = "+lng+ " lat = "+lat);



    }
}
